﻿using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace ConfigurationUtility
{
    public class ConfigUtility
    {
        private static ConfigUtility config;
        [DllImport("kernel32.dll")]
        private static extern int GetPrivateProfileInt(
            string lpAppName,
            string lpKeyName,
            int nDefault,
            string lpFileName
            );

        [DllImport("kernel32.dll")]
        private static extern int GetPrivateProfileString(
            string lpAppName,
            string lpKeyName,
            string lpDefault,
            StringBuilder lpReturnedString,
            int nSize,
            string lpFileName
            );

        [DllImport("kernel32.dll")]
        private static extern int WritePrivateProfileString(
            string lpAppName,
            string lpKeyName,
            string lpString,
            string lpFileName
            );
        private string m_FileName;

        private ConfigUtility()
        {
            m_FileName = Directory.GetCurrentDirectory() + "/main.ini";
        }
        public static ConfigUtility ConfigInfo()
        {
            if (config == null)
            {
                config = new ConfigUtility();
            }
            return config;
        }
        public string GetValue(string sections)
        {
            string[] keys = sections.Split('/');
            string value = string.Empty;
            if (keys.Length == 2)
            {
                value = ReadString(keys[0], keys[1], "");
            }
            return value;
        }
        /// <summary>
        /// [扩展]读取string字符串
        /// </summary>
        /// <param name="section">节</param>
        /// <param name="name">键</param>
        /// <param name="def">默认值</param>
        /// <returns></returns>
        public string ReadString(string section, string name, string def)
        {
            StringBuilder vRetSb = new StringBuilder(2048);
            GetPrivateProfileString(section, name, def, vRetSb, 2048, this.m_FileName);
            return vRetSb.ToString();
        }
        public bool WriteString(string section, string name, string def)
        {
            StringBuilder vRetSb = new StringBuilder(2048);
            WritePrivateProfileString(section, name, def, this.m_FileName);
            return true;
        }
    }
}
